﻿using AutoMapper;
using Domain.Sys;
using DTO;
using IServices.Sys;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Web.Controllers;

namespace Web.Areas.Sys.Controllers
{
    public class PermissionsController : BaseController
    {
        private readonly IAdminUserService _userService;
        private readonly IRoleService _roleService;

        public PermissionsController(IHttpContextAccessor httpContextAccessor, IAdminUserService userService, IRoleService roleService, IMapper mapper)
            : base(httpContextAccessor, mapper)
        {
            _userService = userService;
            _roleService = roleService;
        }

        public async Task<IActionResult> Role(string userId)
        {
            var user = await _userService.GetById(userId);
            var userRole = await _roleService.GetRoleByUserId(userId);

            var roles = userRole.Select(item => item.RoleId).ToList();

            ViewBag.Data = string.Join(",", roles);

            return View(user);
        }

        public async Task<Result> RoleSave(string userId, string roleIds)
        {
            var roles = new List<UserRole>();
            roleIds.Split(',').ToList().ForEach(roleId =>
            {
                if (!string.IsNullOrWhiteSpace(roleId))
                {
                    roles.Add(new UserRole { Id = Guid.NewGuid().ToString(), UserId = userId, RoleId = roleId });
                }
            });
            var status = await _roleService.UpdateRoles(userId, roles, OperatorInfo);
            return status ? Result.Success("保存成功") : Result.Failed(-1, "保存失败");
        }

        public async Task<IActionResult> Module(string roleId)
        {
            var role = await _roleService.GetRoleById(roleId);
            var roleModule = await _roleService.GetModuleByRoleId(roleId);

            var modules = roleModule.Select(item => item.ModuleId).ToList();

            ViewBag.Data = string.Join(",", modules);

            return View(role);
        }

        public async Task<Result> ModuleSave(string roleId, string moduleIds)
        {
            var modules = new List<RoleModule>();
            moduleIds.Split(',').ToList().ForEach(moduleId =>
            {
                if (!string.IsNullOrWhiteSpace(moduleId))
                {
                    modules.Add(new RoleModule { Id = Guid.NewGuid().ToString(), RoleId = roleId, ModuleId = moduleId });
                }
            });

            var status = await _roleService.UpdateModules(roleId, modules, OperatorInfo);
            return status ? Result.Success("保存成功") : Result.Failed(-1, "保存失败");
        }
    }
}